package cwy.flylab.util;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class CollectionUtils {
	
	public static <T> T getItemSafety(List<T> list, int index) {
		if (list != null && index >= 0 && index < list.size()) {
			return list.get(index);
		}
		return null;
	}
	
	public static boolean isEmpty(Collection<?> collection) {
		return collection == null || collection.size() == 0;
	}
	
	public static <T> List<T> getSubList(List<T> list, int row, int page) {
		if(list != null){
			final int N = list.size();
			int start = row * page;
			int end = Math.min(N, start + row);
			if(start < N){
				return list.subList(start, end);
			}
		}
		return null;
	}
	
	public static <K, V> K getKey(Map<K, V> map, V val) {
		Iterator<K> it = map.keySet().iterator();
		while (it.hasNext()) {
			K key = it.next();
			V v = map.get(key);
			if(val.equals(v))
				return key;
		}
		return null;
	}
}
